package me.numark.fragments;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import me.numark.R;
import me.numark.net.AuthorizedJsonObjectRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {@link InputPasswordFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class InputPasswordFragment extends Fragment implements View.OnClickListener {

    private RegisterListener mListener;

    private TextView rightButton;

    private EditText passwordEdit;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment InputPasswordFragment.
     */
    public static InputPasswordFragment newInstance() {
        InputPasswordFragment fragment = new InputPasswordFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    public InputPasswordFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_input_password, container, false);
        passwordEdit = (EditText) view.findViewById(R.id.input_password);
        passwordEdit.requestFocus();
        TextView title = (TextView) view.findViewById(R.id.title);
        title.setText(R.string.set_password);
        view.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        rightButton = (TextView) view.findViewById(R.id.right_text);
        rightButton.setOnClickListener(this);
        rightButton.setText(R.string.next_step);
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (RegisterListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        String password = passwordEdit.getText().toString();
        if (TextUtils.isEmpty(password) || password.length() < 8) {
            Toast.makeText(getActivity(), R.string.password_too_short, Toast.LENGTH_SHORT).show();
            return;
        }
        String uid = Settings.getUid();
        String url = String.format(NetworkConstants.REGISTER_PASSWORD_URL, uid) + "?password="
                + passwordEdit.getText();
        AuthorizedJsonObjectRequest request = new AuthorizedJsonObjectRequest(Request.Method.POST,
                url,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        LogUtils.d("response is " + response);
                        if (response.optBoolean("ret")) {
                            mListener.onNext(InputPasswordFragment.this, null);
                        } else {
                            mListener.onFailure(response.optString("msg",
                                    getString(R.string.set_password_failed)));
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mListener.onFailure(getString(R.string.set_password_failed));
            }
        });
        NetworkHelper.getInstance().getRequestQueue().add(request);
        NetworkHelper.getInstance().getRequestQueue().start();
        mListener.onShowProgress(getString(R.string.setting_password));
    }

}
